import "./reset.css";
import dayjs from "dayjs";
import roleForm from "../form/role.vue";
import editForm from "../form/index.vue";
import { zxcvbn } from "@zxcvbn-ts/core";
import { message } from "@/utils/message";
import { usePublicHooks } from "../../hooks";
import { addDialog } from "@/components/ReDialog";
import { type PaginationProps } from "@pureadmin/table";
import type { FormItemProps, RoleFormItemProps } from "../utils/types";
import { isAllEmpty } from "@pureadmin/utils";

import { userSearch, userUpsert } from "@/api/user/user";
import { resetPassword } from "@/api/user/security";

import {
  ElForm,
  ElInput,
  ElFormItem,
  ElProgress,
  ElMessageBox
} from "element-plus";

import {
  type Ref,
  h,
  ref,
  toRaw,
  watch,
  computed,
  reactive,
  onMounted
} from "vue";

import { PageParam } from "@/api";
import {
  UserData,
  UserSearch,
  UserUpsert,
  ResetPassword
} from "@/api/user";

export function useUser(tableRef: Ref) {
  const form = reactive({
    id: undefined,
    username: undefined,
    nickname: undefined,
    valid: undefined
  });
  const formRef = ref();
  const ruleFormRef = ref();
  const dataList: Ref<UserData[]> = ref([]);
  const loading = ref(true);

  const switchLoadMap: Ref<any[]> = ref([]);
  const { switchStyle } = usePublicHooks();
  const selectedNum = ref(0);
  const pagination = reactive<PaginationProps>({
    total: 0,
    pageSize: 10,
    currentPage: 1,
    pageSizes: [10, 20, 50, 100],
    background: true
  });
  const columns: TableColumnList = [
    {
      label: "勾选列", // 如果需要表格多选，此处label必须设置
      type: "selection",
      fixed: "left",
      reserveSelection: true // 数据刷新后保留选项
    },
    {
      label: "ID",
      prop: "id",
      width: 90
    },
    {
      label: "头像",
      prop: "avatar",
      cellRenderer: ({ row }) => (
        <el-image
          fit="cover"
          preview-teleported={true}
          src={row.avatarUrl}
          preview-src-list={Array.of(row.avatarUrl)}
          class="w-[24px] h-[24px] rounded-full align-middle"
        />
      ),
      width: 90
    },
    {
      label: "用户名",
      prop: "username",
      minWidth: 130
    },
    {
      label: "昵称",
      prop: "nickname",
      minWidth: 130
    },
    {
      label: "状态",
      prop: "valid",
      minWidth: 90,
      cellRenderer: scope => (
        <el-switch
          size={scope.props.size === "small" ? "small" : "default"}
          loading={switchLoadMap.value[scope.index]?.loading}
          v-model={scope.row.valid}
          active-value={true}
          inactive-value={false}
          active-text="启用"
          inactive-text="停用"
          inline-prompt
          style={switchStyle.value}
          onChange={() => onChange(scope as any)}
        />
      )
    },
    {
      label: "创建时间",
      minWidth: 90,
      prop: "createTime",
      formatter: ({ createTime }) =>
        dayjs(createTime).format("YYYY-MM-DD HH:mm:ss")
    },
    {
      label: "操作",
      fixed: "right",
      width: 180,
      slot: "operation"
    }
  ];
  const buttonClass = computed(() => {
    return [
      "!h-[20px]",
      "reset-margin",
      "!text-gray-500",
      "dark:!text-white",
      "dark:hover:!text-primary"
    ];
  });
  // 重置的新密码
  const pwdForm = reactive({
    newPwd: ""
  });
  const pwdProgress = [
    { color: "#e74242", text: "非常弱" },
    { color: "#EFBD47", text: "弱" },
    { color: "#ffa500", text: "一般" },
    { color: "#1bbf1b", text: "强" },
    { color: "#008000", text: "非常强" }
  ];
  // 当前密码强度（0-4）
  const curScore = ref();
  const roleOptions = ref([]);

  function onChange({ row, index }: { row: UserData; index: number }) {
    ElMessageBox.confirm(
      `确认要<strong>${
        row.valid === true ? "启用" : "停用"
      }</strong> <strong style='color:var(--el-color-primary)'>${
        row.username
      }</strong> 用户吗?`,
      "系统提示",
      {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
        dangerouslyUseHTMLString: true,
        draggable: true
      }
    )
      .then(() => {
        switchLoadMap.value[index] = Object.assign(
          {},
          switchLoadMap.value[index],
          {
            loading: true
          }
        );
        setTimeout(() => {
          const param: UserUpsert = {
            id: row.id,
            valid: row.valid
          };
          userUpsert({ param })
            .then(({ data }) => {
              console.debug("data", data);
              switchLoadMap.value[index] = Object.assign(
                {},
                switchLoadMap.value[index],
                {
                  loading: false
                }
              );
              message("已成功修改用户状态", {
                type: "success"
              });
            })
            .catch(error => {
              console.error("error", error);
            });
        }, 300);
      })
      .catch(() => {
        row.valid === true ? (row.valid = true) : (row.valid = false);
      });
  }

  function handleUpdate(row: any) {
    console.debug(row);
  }

  function handleDelete(row: { id: any }) {
    console.debug("row", row);
    message(`暂未支持此项功能！`, { type: "error" });
    onSearch();
  }

  function handleSizeChange(val: number) {
    console.debug(`${val} items per page`);
    pagination.pageSize = val;
    onSearch();
  }

  function handleCurrentChange(val: number) {
    console.debug(`current page: ${val}`);
    pagination.currentPage = val;
    onSearch();
  }

  /** 当CheckBox选择项发生变化时会触发该事件 */
  function handleSelectionChange(val: string | any[]) {
    selectedNum.value = val.length;
    // 重置表格高度
    tableRef.value.setAdaptive();
  }

  /** 取消选择 */
  function onSelectionCancel() {
    selectedNum.value = 0;
    // 用于多选表格，清空用户的选择
    tableRef.value.getTableRef().clearSelection();
  }

  /** 批量删除 */
  function onbatchDel() {
    // 返回当前选中的行
    const curSelected = tableRef.value.getTableRef().getSelectionRows();
    console.debug("curSelected", curSelected);
    // 接下来根据实际业务，通过选中行的某项数据，比如下面的id，调用接口进行批量删除
    message(`暂未支持此项功能！`, {
      type: "error"
    });
    tableRef.value.getTableRef().clearSelection();
  }

  async function onSearch() {
    loading.value = true;
    const { id, username, nickname, valid } = toRaw(form);
    const param: PageParam<UserSearch> = {
      page: pagination.currentPage,
      size: pagination.pageSize,
      param: {
        id: id ? id : undefined,
        username: username ? username : undefined,
        nickname: nickname ? nickname : undefined,
        valid: valid
      }
    };
    userSearch({ param })
      .then(({ data }) => {
        dataList.value = data.list ?? [];
        pagination.total = data.total ?? 0;
        pagination.pageSize = data.size ?? 10;
        pagination.currentPage = data.page ?? 1;
      })
      .catch(error => {
        console.error("error", error);
        loading.value = false;
      });

    setTimeout(() => {
      loading.value = false;
    }, 500);
  }

  const resetForm = (formEl: { resetFields: () => void }) => {
    if (!formEl) return;
    formEl.resetFields();
    onSearch();
  };

  function openDialog(title = "新增", row?: FormItemProps) {
    addDialog({
      title: `${title}用户`,
      props: {
        formInline: {
          title,
          id: row?.id ?? undefined,
          username: row?.username ?? "",
          valid: row?.valid ?? true
        }
      },
      width: "46%",
      draggable: true,
      fullscreenIcon: true,
      closeOnClickModal: false,
      contentRenderer: () => h(editForm, { ref: formRef }),
      beforeSure: (done, { options }) => {
        const FormRef = formRef.value.getRef();
        const curData = options.props.formInline as FormItemProps;
        function chores() {
          message(`您${title}了用户名称为${curData.username}的这条数据`, {
            type: "success"
          });
          done(); // 关闭弹框
          onSearch(); // 刷新表格数据
        }
        FormRef.validate((valid: any) => {
          if (valid) {
            console.debug("curData", curData);
            // 表单规则校验通过
            if (title === "新增") {
              // 实际开发先调用新增接口，再进行下面操作
              const userUpsertParam: UserUpsert = {
                username: curData.username,
                valid: curData.valid
              };
              userUpsert({ param: userUpsertParam })
                .then(({ data }) => {
                  console.debug("data", data);
                  chores();
                })
                .catch(error => {
                  console.error("error", error);
                });
            } else {
              // 实际开发先调用编辑接口，再进行下面操作
              const userUpsertParam: UserUpsert = {
                id: curData.id,
                username: curData.username
              };
              userUpsert({ param: userUpsertParam })
                .then(({ data }) => {
                  console.debug("data", data);
                  chores();
                })
                .catch(error => {
                  console.error("error", error);
                });
            }
          }
        });
      }
    });
  }

  watch(
    pwdForm,
    ({ newPwd }) =>
      (curScore.value = isAllEmpty(newPwd) ? -1 : zxcvbn(newPwd).score)
  );

  /** 重置密码 */
  function handleReset(row: { id: any; username: any }) {
    addDialog({
      title: `重置 ${row.username} 用户的密码`,
      width: "30%",
      draggable: true,
      closeOnClickModal: false,
      contentRenderer: () => (
        <>
          <ElForm ref={ruleFormRef} model={pwdForm}>
            <ElFormItem
              prop="newPwd"
              rules={[
                {
                  required: false,
                  message: "请输入新密码",
                  trigger: "blur"
                }
              ]}
            >
              <ElInput
                clearable
                show-password
                type="password"
                v-model={pwdForm.newPwd}
                placeholder="请输入新密码"
              />
            </ElFormItem>
          </ElForm>
          <div class="mt-4 flex">
            {pwdProgress.map(({ color, text }, idx) => (
              <div
                class="w-[19vw]"
                style={{ marginLeft: idx !== 0 ? "4px" : 0 }}
              >
                <ElProgress
                  striped
                  striped-flow
                  duration={curScore.value === idx ? 6 : 0}
                  percentage={curScore.value >= idx ? 100 : 0}
                  color={color}
                  stroke-width={10}
                  show-text={false}
                />
                <p
                  class="text-center"
                  style={{ color: curScore.value === idx ? color : "" }}
                >
                  {text}
                </p>
              </div>
            ))}
          </div>
        </>
      ),
      closeCallBack: () => (pwdForm.newPwd = ""),
      beforeSure: done => {
        ruleFormRef.value.validate((valid: any) => {
          if (valid) {
            // 表单规则校验通过
            const param: ResetPassword = {
              id: row.id,
              password: pwdForm.newPwd ? pwdForm.newPwd : undefined
            };
            resetPassword({ param })
              .then(({ data }) => {
                console.debug("data", data);
                message(`已成功重置 ${row.username} 用户的密码`, {
                  type: "success"
                });
                console.debug(pwdForm.newPwd);
                done(); // 关闭弹框
                onSearch(); // 刷新表格数据
              })
              .catch(error => {
                console.error("error", error);
              });
          }
        });
      }
    });
  }

  /** 分配角色 */
  async function handleRole(row: UserData) {
    message(`暂未支持此项功能！`, {
      type: "error"
    });
    return;
    // 选中的角色列表
    // const ids = (await getRoleIds({ userId: row.id })).data ?? [];
    const ids: any[] = [];
    addDialog({
      title: `分配 ${row.username} 用户的角色`,
      props: {
        formInline: {
          username: row?.username ?? "",
          nickname: row?.nickname ?? "",
          roleOptions: roleOptions.value ?? [],
          ids
        }
      },
      width: "400px",
      draggable: true,
      fullscreenIcon: true,
      closeOnClickModal: false,
      contentRenderer: () => h(roleForm),
      beforeSure: (done, { options }) => {
        const curData = options.props.formInline as RoleFormItemProps;
        console.debug("curIds", curData.ids);
        // 根据实际业务使用curData.ids和row里的某些字段去调用修改角色接口即可
        done(); // 关闭弹框
      }
    });
  }

  onMounted(async () => {
    onSearch();

    // 角色列表
    // roleOptions.value = (await getAllRoleList()).data;
    roleOptions.value = [];
  });

  return {
    form,
    loading,
    columns,
    dataList,
    selectedNum,
    pagination,
    buttonClass,
    onSearch,
    resetForm,
    onbatchDel,
    openDialog,
    handleUpdate,
    handleDelete,
    handleReset,
    handleRole,
    handleSizeChange,
    onSelectionCancel,
    handleCurrentChange,
    handleSelectionChange
  };
}
